package com.quickask.serviceImpl;

import com.quickask.common.Pager;
import com.quickask.dao.AnswerLocationSetDao;
import com.quickask.dao.AnswerSetDao;
import com.quickask.dao.QuestionSetDao;
import com.quickask.dao.UserPrivilegeDao;
import com.quickask.entity.*;
import com.quickask.operate.data.Constants;
import com.quickask.operate.data.ResultCode;
import com.quickask.operate.encode.Geohash;
import com.quickask.service.AnswerService;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by NaSa on 2015/10/2.
 */
public class AnswerServiceImpl extends BaseServiceImpl implements AnswerService {

    private AnswerSetDao answerSetDao;
    private AnswerLocationSetDao answerLocationSetDao;
    private QuestionSetDao questionSetDao;
    private UserPrivilegeDao userPrivilegeDao;

    protected Logger logger = Logger.getLogger(this.getClass());

    public void setAnswerSetDao(AnswerSetDao answerSetDao) {
        this.answerSetDao = answerSetDao;
    }

    public void setAnswerLocationSetDao(AnswerLocationSetDao answerLocationSetDao) {
        this.answerLocationSetDao = answerLocationSetDao;
    }

    public void setQuestionSetDao(QuestionSetDao questionSetDao) {
        this.questionSetDao = questionSetDao;
    }

    public void setUserPrivilegeDao(UserPrivilegeDao userPrivilegeDao) {
        this.userPrivilegeDao = userPrivilegeDao;
    }

    /**
     * 添加问题
     * @param answerJson 答案json数据
     * @param refreshToken 用户token
     */
    @Override
    public AsknowAnswerSet addAnswer(String answerJson,String refreshToken) {
        try {
            JSONObject jsonObject = new JSONObject(answerJson);
            AsknowAnswerSetEntity asknowAnswerSetEntity = new AsknowAnswerSetEntity();
            asknowAnswerSetEntity.setUserId(jsonObject.optInt("userId"));
            asknowAnswerSetEntity.setAnswerTime(new Timestamp(System.currentTimeMillis()));
            asknowAnswerSetEntity.setQuestionId(jsonObject.optInt("questionId"));
            asknowAnswerSetEntity.setAnswerAdoptNum(0);
            asknowAnswerSetEntity.setAnswerIsAdopt((byte) 0);
            asknowAnswerSetEntity.setAnswerContent(jsonObject.optString("answerContent"));
            //asknowAnswerSetEntity.setAnswerImageUrls(jsonObject.optString("answerImageUrls"));
            //asknowAnswerSetEntity.setAnswerVoiceUrls(jsonObject.optString("answerVoiceUrls"));
            asknowAnswerSetEntity.setAnswerIsReport((byte) 0);
            asknowAnswerSetEntity.setAnswerStars(0);
            answerSetDao.save(asknowAnswerSetEntity);

            AsknowAnswerLocationSetEntity asknowAnswerLocationSetEntity = new AsknowAnswerLocationSetEntity();
            asknowAnswerLocationSetEntity.setAnswerId(asknowAnswerSetEntity.getAnswerId());
            asknowAnswerLocationSetEntity.setLatitude(jsonObject.optDouble("latitude"));
            asknowAnswerLocationSetEntity.setLongitude(jsonObject.optDouble("longitude"));
            asknowAnswerLocationSetEntity.setAltitude(jsonObject.optDouble("altitude"));
            asknowAnswerLocationSetEntity.setProvinceCode(jsonObject.optString("provinceCode"));
            asknowAnswerLocationSetEntity.setCityCode(jsonObject.optString("cityCode"));
            asknowAnswerLocationSetEntity.setBlockCode(jsonObject.optString("blockCode"));
            asknowAnswerLocationSetEntity.setLocationDetail(jsonObject.optString("locationDetail"));
            asknowAnswerLocationSetEntity.setGeohash(new Geohash().encode(jsonObject.optDouble("latitude"), jsonObject.optDouble("longitude")));

            asknowAnswerSetEntity.setAsknowAnswerLocationSetEntity(asknowAnswerLocationSetEntity);
            questionSetDao.updateQuestionAnswernum(asknowAnswerSetEntity.getQuestionId());

            return setAsknowAnswerSet(userPrivilegeDao.get(jsonObject.optInt("userId")),asknowAnswerSetEntity,null);
        } catch (Exception e) {
            logger.error("add answer fail,due to " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取答案列表并根据answerId排序
     *
     * @param pageNo     页码
     * @param pageSize   分页大小
     * @param questionId 问题Id
     * @param properties 其它参数属性(latitude,longitude...)
     * @return
     */
    @Override
    public List<AsknowAnswerSet> findAnswerListOrderByAnswerId(int pageNo, int pageSize, int questionId, Map<String, Object> properties) {
        List<AsknowAnswerSet> asknowAnswerSetList = new ArrayList<AsknowAnswerSet>();
        Pager<AsknowAnswerSetEntity> asknowAnswerSetEntityPager = answerSetDao.findAnswerPagerByQuestionId(pageNo, pageSize, questionId);
        for (AsknowAnswerSetEntity asknowAnswerSetEntity : asknowAnswerSetEntityPager.getPageRecords()) {
            AsknowAnswerSet asknowAnswerSet = setAsknowAnswerSet(userPrivilegeDao.get(asknowAnswerSetEntity.getUserId()),asknowAnswerSetEntity,properties);
            asknowAnswerSetList.add(asknowAnswerSet);
        }
        return asknowAnswerSetList;
    }

    /**
     * 获取答案列表并根据answerId排序
     *
     * @param pageNo     页码
     * @param pageSize   分页大小
     * @param userId     问题Id
     * @param properties 其它参数属性(latitude,longitude...)
     * @return
     */
    @Override
    public List<AsknowAnswerSet> findAnswerListByUserId(int pageNo, int pageSize, int userId, Map<String, Object> properties) {
        List<AsknowAnswerSet> asknowAnswerSetList = new ArrayList<AsknowAnswerSet>();
        Pager<AsknowAnswerSetEntity> asknowAnswerSetEntityPager = answerSetDao.findAnswerPagerByUserId(pageNo,pageSize,userId);
        for (AsknowAnswerSetEntity asknowAnswerSetEntity : asknowAnswerSetEntityPager.getPageRecords()) {
            AsknowAnswerSet asknowAnswerSet = setAsknowAnswerSet(userPrivilegeDao.get(asknowAnswerSetEntity.getUserId()),asknowAnswerSetEntity,properties);
            asknowAnswerSetList.add(asknowAnswerSet);
        }
        return asknowAnswerSetList;
    }

    /**
     * 添加答案采纳数
     *
     * @param answerId 答案id
     * @return
     */
    @Override
    public int AddAnswerAdoptNum(int answerId) {
        AsknowAnswerSetEntity answerSetEntity = answerSetDao.get(answerId);
        if (null == answerSetEntity) {
            logger.warn("答案id不存在！");
            return ResultCode.ANSWER_ERROR;
        }
        answerSetEntity.setAnswerAdoptNum(answerSetEntity.getAnswerAdoptNum() + 1);
        answerSetDao.update(answerSetEntity);
        return ResultCode.SUCCESS;
    }

    /**
     * 答案被采纳
     *
     * @param answerId 答案id
     * @return
     */
    @Override
    public int setAnswerAdopt(int answerId) {
        AsknowAnswerSetEntity answerSetEntity = answerSetDao.get(answerId);
        if (null == answerSetEntity) {
            return ResultCode.ANSWER_ERROR;
        }
        answerSetEntity.setAnswerIsAdopt((byte) 1);
        answerSetDao.update(answerSetEntity);
        return ResultCode.SUCCESS;
    }

    /**
     * 检举答案
     *
     * @param answerId 答案id
     * @param userId   检举人id
     * @return
     */
    @Override
    public int reportAnswer(int answerId, int userId) {
        AsknowAnswerSetEntity answerSetEntity = answerSetDao.get(answerId);
        if (null == answerSetEntity) {
            return ResultCode.ANSWER_ERROR;
        }
        answerSetEntity.setAnswerIsReport((byte) 1);
        answerSetDao.update(answerSetEntity);
        return ResultCode.SUCCESS;
    }

    //设置asknowAnswerSet实体并返回
    public AsknowAnswerSet setAsknowAnswerSet(AsknowUserPrivilegeEntity asknowUserPrivilegeEntity, AsknowAnswerSetEntity asknowAnswerSetEntity, Map<String, Object> properties) {
        AsknowAnswerSet asknowAnswerSet = new AsknowAnswerSet();
        asknowAnswerSet.setUserId(asknowUserPrivilegeEntity.getUserId());
        asknowAnswerSet.setUserNickname(asknowUserPrivilegeEntity.getUserNickname());
        asknowAnswerSet.setUserIcon(asknowUserPrivilegeEntity.getUserIcon());
        asknowAnswerSet.setAnswerId(asknowAnswerSetEntity.getAnswerId());
        asknowAnswerSet.setAnswerTime(asknowAnswerSetEntity.getAnswerTime());
        asknowAnswerSet.setQuestionId(asknowAnswerSetEntity.getQuestionId());
        asknowAnswerSet.setAnswerAdoptNum(asknowAnswerSetEntity.getAnswerAdoptNum());
        asknowAnswerSet.setAnswerIsAdopt(asknowAnswerSetEntity.getAnswerIsAdopt());
        asknowAnswerSet.setAnswerContent(asknowAnswerSetEntity.getAnswerContent());
        asknowAnswerSet.setAnswerImageUrls(asknowAnswerSetEntity.getAnswerImageUrls());
        asknowAnswerSet.setAnswerVoiceUrls(asknowAnswerSetEntity.getAnswerVoiceUrls());
        asknowAnswerSet.setAnswerIsReport(asknowAnswerSetEntity.getAnswerIsReport());
        asknowAnswerSet.setLocationDetail(asknowAnswerSetEntity.getAsknowAnswerLocationSetEntity().getLocationDetail());
        asknowAnswerSet.setAnswerStars(asknowAnswerSetEntity.getAnswerStars());
        if (null != properties && properties.containsKey("latitude")) {
            asknowAnswerSet.setDistance(Constants.computeDistance((Double) properties.get("latitude"), (Double) properties.get("longitude"), asknowAnswerSetEntity.getAsknowAnswerLocationSetEntity().getLatitude(),
                    asknowAnswerSetEntity.getAsknowAnswerLocationSetEntity().getLongitude()));
        } else {
            asknowAnswerSet.setDistance(0.0d);
        }
        return asknowAnswerSet;
    }
}
